package com.anlu.base.sign;


import com.alibaba.fastjson2.JSON;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * Description:
 *
 * @author Destiny
 * @date 2022-03-25
 */
public class SignAndEncryptTest {

    private final static Logger log = LoggerFactory.getLogger(SignAndEncryptTest.class);
    public static final String  SIGN_ALGORITHMS = "SHA1WithRSA";
    public static final String CHATSET = "utf-8";



    public static String publicKey_A = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsnen01CdQc2zh/HihCNNYI6u7AFXf/NrZ/9auPvFsJcK1cWj5EFBU3lrts2OTvrmYVurhABg2g/Ya7glzUt6DwUojHOWtpwFxSH1v7FUJMvxDsbd4GXKRdWqMkqkcCMQYDpGpshbL3IAWYIw6pgnBcKksbzkDrZCZMAyHa1bB3zh5uEm9mcrRlBUGirbPNVt++3ztIfdc4Vp5hbw++daNMFr/VGDohMVg3Dlk4ZktDgHc5nakXkE8hSr6UDTw45JpfZZ0dP9XTi/CSVQdoYD+dsJIZ8uletlbrErRfZEJNx/k0w88P4kfGteNBGhlzzVo45tMkHT33O8QB6JxI4xVQIDAQAB";
    public static String privateKey_A = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCyd6fTUJ1BzbOH8eKEI01gjq7sAVd/82tn/1q4+8WwlwrVxaPkQUFTeWu2zY5O+uZhW6uEAGDaD9hruCXNS3oPBSiMc5a2nAXFIfW/sVQky/EOxt3gZcpF1aoySqRwIxBgOkamyFsvcgBZgjDqmCcFwqSxvOQOtkJkwDIdrVsHfOHm4Sb2ZytGUFQaKts81W377fO0h91z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8GyoyoAGVFLGsLeMdUfJeVbzrLyJEHrlBStEbcAW6rwLJ/5jySDQnzdJaLo7TsUnFXKAOgl24gPRtFmLB5mNN1TWJS86x2esMB+LrK33AoGADEDHIUtulc4zclLH9MJj7JcZPkgVz5llJ1jQj3fOu4iPc9TNvV2gV2kWU446gyMmRrQ2We1awnrjaeSzeFnf0OhL+yTzNUmRLMYWZhja/KMhr7b9vVRCCrysZJod+MWodEH+HIJlu9RGIxv7fNNy1S4yRU92OQU43XQ1S93eaEE=";

    public static String publicKey_B = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAv8GjRufWGPI7Xe6caZ5h5PbnRIQVzD4P1gDjKZaibcxcApGEaqFkT3Am2U6iKv6paELuwxy+dUL1Jvbs09QljuHgDB9SV0VxSM5LscpCmWJ5P1V6Y/QiholCQHCFR6ok6oE2HWGRw/bPQWr/gHfa2zNPu+CB64cbOxLHIQYIRji47tyywAL5ABhF1msZY2vW8xaFKHGq74sxNpf8s0NUnRnVRANjHtuDa/zvrHim45gqBWg+3gPVSQyPU3ydMoj0AiORJQmqprHaZDB7BufpTEZA6I2WElsKJcsGMdwfSd1s0B1iCzrkMmT30n/XXxyw8qQGsvJvQ2V90QiAV9bV+wIDAQAB";
    public static String privateKey_B = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC/waNG59YY8jtd7pxpnmHk9udEhBXMPg/WAOMplqJtzFwCkYRqoWRPcCbZTqIq/qloQu7DHL51QvUm9uzT1CWO4eAMH1JXRXFIzkuxykKZYnk/VXpj9CKGiUJAcIVHqiTqgTYdYZHD9s9Bav+Ad9rbM0+74IHrhxs7EschBghGOLju3LLAAvkAGEXWaxlja9bzFoUocarvizE2l/yzQ1SdGdVEA2Me24Nr/O+seKbjmCoFaD7eA9VJDI9TfJ0yiPQCI5ElCaqmsdpkMHsG5+lMRkDojZYSWwolywYx3B9J3WzQHWILOuQyZPfSf9dfHLDypAay8m9DZX3RC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LtTdiloSI6bxgli0Rm8T+6wD6y9JNnWsibYydGx9pDn6w2qihuP1QcKruHUiZ7V8aahhD4o4e/a+IgRzNYcQh4CngUzL+XymlqQVbDSaiEiVi/qSNv+i9mgeF/mSYbYcZjhFPjzdOy3hvtO3GtjDSMQw=";

    // 封装发送的消息
    public static Map<String,String> communicationParams = null;

    public static void main(String[] args) {

        // A给B发消息
        ASendMsgToB();


        // B接收来自A的消息
        BReceiveFromA();
    }


    /**
     * A给B发消息，首先A-B交换公钥，A拥有 privateKey_A 和 publicKey_B
     *
     * A使用publicKey_B加密消息，再使用privateKey_A对密文签名，然后将密文和签名发给B
     */
    public static void ASendMsgToB(){

        // 消息明文
        String msg = "你好";

        // 加密
        String encryptMsg = encryptByPublicKey(msg,publicKey_B);

        // 签名
        String sign = signByPrivateKey(encryptMsg,privateKey_A);

        // 发送消息
        communicationParams = new HashMap<String,String>();
        communicationParams.put("encryptMsg",encryptMsg);
        communicationParams.put("sign",sign);
        log.info("A发送给B的消息:{}", JSON.toJSONString(communicationParams));

        log.info("-------------------------------------------------");
    }

    /**
     * B接收A的消息，首先A-B交换公钥，B拥有 privateKey_B 和 publicKey_A
     *
     * B收到消息后，先使用publicKey_A验签，再使用privateKey_B解密
     */
    public static void BReceiveFromA(){


        // 接收消息
        Map<String,String> receiveMsg = communicationParams;
        log.info("B接收到A的消息:{}", JSON.toJSONString(receiveMsg));
        String sign = receiveMsg.get("sign");
        String encryptMsg = receiveMsg.get("encryptMsg");

        // 验签
        Boolean tf = verifySignPublicKey(encryptMsg,publicKey_A,sign);
        if(tf){
            log.info("验签通过，说明这个信息是B认可的用户发来的");
        }

        // 解密
        String msg = decryptByPrivateKey(encryptMsg,privateKey_B);
        log.info("解密成功，说明这个信息就是发给B的");


        log.info("B收到的消息:{}", msg);
    }


    /**
     * RSA签名
     * @param content 待签名数据
     * @param privateKey 商户私钥
     * @return 签名值
     */
    public static String signByPrivateKey(String content, String privateKey)
    {
        try{
            PKCS8EncodedKeySpec priPKCS8    = new PKCS8EncodedKeySpec(  Base64.decodeBase64(privateKey) );
            KeyFactory keyf                 = KeyFactory.getInstance("RSA");
            PrivateKey priKey               = keyf.generatePrivate(priPKCS8);

            Signature signature = Signature.getInstance(SIGN_ALGORITHMS);

            signature.initSign(priKey);
            signature.update( content.getBytes(CHATSET) );

            byte[] signed = signature.sign();

            return Base64.encodeBase64String(signed);

        }catch (Exception e){
            log.error(e.getMessage(), e);
        }

        return null;
    }

    /**
     * RSA验签名检查
     * @param content 待签名数据
     * @param sign 签名值
     * @param publicKey 公钥
     * @return 布尔值
     */
    public static boolean verifySignPublicKey(String content, String publicKey, String sign)
    {
        try{
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            byte[] encodedKey =  Base64.decodeBase64(publicKey);
            PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));

            Signature signature = Signature.getInstance(SIGN_ALGORITHMS);

            signature.initVerify(pubKey);
            signature.update( content.getBytes(CHATSET) );

            boolean bverify = signature.verify(  Base64.decodeBase64(sign) );
            return bverify;

        }catch (Exception e){
            log.error(e.getMessage(), e);
        }

        return false;
    }

    /**
     * RSA公钥加密
     * @param str 加密字符串
     * @param publicKey 公钥
     * @return 密文
     */
    public static String encryptByPublicKey( String str, String publicKey ) {

        try{

            //base64编码的公钥
            byte[] decoded =  Base64.decodeBase64(publicKey);
            RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));

            //RSA加密
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            String outStr = org.apache.commons.codec.binary.Base64.encodeBase64String(cipher.doFinal(str.getBytes(CHATSET)));
            return outStr;

        }catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return null;
    }

    /**
     * RSA私钥解密
     * @param str 加密字符串
     * @param privateKey 私钥
     * @return 明文
     */
    public static String decryptByPrivateKey(String str, String privateKey){

        try{

            //64位解码加密后的字符串
            byte[] inputByte =  Base64.decodeBase64(str.getBytes(CHATSET));
            //base64编码的私钥
            byte[] decoded = org.apache.commons.codec.binary. Base64.decodeBase64(privateKey);
            RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));

            //RSA解密
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, priKey);
            String outStr = new String(cipher.doFinal(inputByte));
            return outStr;

        }catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return null;
    }

}
